﻿using System;
using System.Windows;
using System.Windows.Navigation;
using Windows.Phone.Storage.SharedAccess;

namespace WeiboSdkSample
{
    /// <summary>
    /// Mapper class for Uri Association
    /// </summary>
    class AssociationUriMapper : UriMapperBase
    {
        public override Uri MapUri(Uri uri)
        {
            string tempUri = System.Net.HttpUtility.UrlDecode(uri.ToString());
            //System.Windows.MessageBox.Show(tempUri);

            //if launch via weibo association
            if (tempUri.Contains("/Protocol?encodedLaunchUri"))
            {
                //SSO 授权
                if (tempUri.Contains("sinaweiboback:authback"))
                {
                    var query = tempUri.Split('?');
                    if (query.Length > 1)
                    {
                        //System.Windows.MessageBox.Show(tempUri);
                        string result = GetQueryStringValue(tempUri, "result");
                        if (result == "cancel")
                        {
                            MessageBox.Show("sso canceled");
                        }
                        else if (result == "fail")
                        {
                            MessageBox.Show("sso failed");
                        }
                        else if (result == "ok")
                        {
                            App.Nickname = GetQueryStringValue(tempUri, "screen_name");
                            App.AccessToken = GetQueryStringValue(tempUri, "access_token"); ;
                            App.Uid = GetQueryStringValue(tempUri, "uid");
                            return new Uri("/PageViews/SsoSharePage.xaml", UriKind.Relative);
                        }                        
                    }
                    return new Uri("/MainPage.xaml", UriKind.Relative);
                }
            }
            // Otherwise perform normal launch.
            return uri;
        }

        private string GetQueryStringValue(string url, string key)
        {
            string param = url.Substring(url.LastIndexOf('?') + 1);
            string[] paramsKeys = param.Split('&');
            System.Collections.Generic.Dictionary<string, string> keys = new System.Collections.Generic.Dictionary<string, string>();
            for (int i = 0; i < paramsKeys.Length; i++)
            {
                string k = (paramsKeys[i]).Substring(0, (paramsKeys[i]).IndexOf('='));
                string value = (paramsKeys[i]).Substring((paramsKeys[i]).IndexOf('=') + 1);
                keys[k] = value;
            }

            if (keys.ContainsKey(key))
            {
                return keys[key];
            }
            return "";
        }

    }
}
